<?php
	/**********************
		created by: Moses Chan
		created on: 08-11-12
			edited on: 10-11-12: started to implement session storage id'd by client IP addr
			edited on: 11-11-12
			edited on: 12-11-12
			edited on: 13-11-12: completed implementation of session storage and retrieval
			edited on: 15-11-12: now getting the password from the database
		
		DESCRIPTION:
			gets username/password pairs from file to
			validate against user supplied credentials
			
			creates a form to capture user input
			
			upon successful login:
				1. starts a session and sets $_SESSION['loggedAs'] to username
				//2. redirects to $goHere - to be implemented
				
		BUGS:
			client gets a "freebie" login chance... input form always shows up once
				-resolved on 14-11-12
	**********************/

	//redirect here after successful login
	//$goHere = 'login.php';
	
	$timeOut = 300; //session timeout period in sec (5min)
	$loggedTOut = 1800; //logged user timeout period in sec (30min)
	$oldSession = '';
	
	//get session from db if available
	$dbHost = 'localhost';
	//$dbPort = '8889';
	$dbUser = 'root';
	$dbPass = 'root';
	$dbSelect = 'TravelExperts';
	$dbh = new mysqli($dbHost, $dbUser, $dbPass, $dbSelect);

	//check connection
	if($dbh->connect_errno) {
		echo 'database connection failed: '.$dbh->connect_error;
		exit();
	}	
	
	
	//create a sessions table in the database
	$createSeshTable = "CREATE TABLE Sessions
							(ipAddr varchar(50) Unique,
							seshId varchar(500),
							PRIMARY KEY(ipAddr));";
	
	if(!$dbh->query($createSeshTable)) 
	//	echo "Table creation failed: (" . $dbh->errno . ") " . $dbh->error;
	
	
	$remoteAddr ='"'.$_SERVER['REMOTE_ADDR'].'"';
	//$remoteAddr = '"192.168.0.101"'; 
	//echo 'connected from: '.$remoteAddr;
	//for some reason the db won't fetch matching IP addr without the " " around it
	//so we add them and store it together in the db

/*	echo "SELECT seshId FROM Sessions WHERE ipAddr=$remoteAddr";
	if($result = $dbh->query("SELECT seshId FROM Sessions WHERE ipAddr=$remoteAddr"))
		{
			echo 'got the result';
			while ($row = $result->fetch_row()) {
				echo "\n result is: ".$row[0];
			}
		}
	else {echo 'contents: '.var_dump($result);
		
		printf("Connect failed: %s\n", $dbh->connect_error);}
*/

	if($sqlStm = $dbh->prepare("SELECT seshId FROM Sessions WHERE ipAddr=?")) {
		$sqlStm->bind_param("s", $remoteAddr);
		$sqlStm->execute(); //begin searching database for a previous session
		$sqlStm->bind_result($oldSession);
	
		if ($sqlStm->fetch()) {
			//echo ' - oldsession data - '.$oldSession.'  - ';//debug line
			session_decode($oldSession); //decode the old session
			//echo ' - decoded lastAttempt - '.$_SESSION['lastAttempt'];//debug line
			//echo 'last attempt at: '.var_dump($_SESSION['lastAttempt']);
			$sinceLast = time() - $_SESSION['lastAttempt'];
			//echo 'time since last attempt: '.var_dump($last);//debug line
			if ($sinceLast < $timeOut) {
				//set $loginAttempts to saved value if less than $timeOut
				$loginAttempts = ++$_SESSION['attempts'];
			//	echo 'got loginAttempts from stored session '.$_SESSION['attempts'];//debug line
			}
				//else reset $loginAttempts
			else { $loginAttempts = 0; }
		}
		else {  //no record found, init $loginAttempts = 0 and lastAttempt to current time
			//echo 'no record found';
			$firstTime = "t"; //remember this for later
			$loginAttempts = 0;
			$_SESSION['lastAttempt'] = time();
		}
		
		$sqlStm->close(); //release resources
	} 
			
			
	//do this only if nobody is logged in else just print a welcome message
	if(!isset($_SESSION['loggedAs'])) {
	
		//some variables
		//$userHashPairs = array();
		$errorMsg = '';

/*getting this through $_SESSION['attempts'] instead
		//log the amount of login attempts
		if(isset($_POST['attempts'])) {
			$loginAttempts = ++$_POST['attempts'];
		}
		
		else { 
			
			$loginAttempts = 0; 
			//to-do: set $loginAttempts to $_SESSION['attempts']
		}
*/

/***************** using the database instead of a file
		//get the username/password pairs from the file
		$fileName = "users.txt";
		$fileHandle = fopen($fileName, "r");

	
		while(!feof($fileHandle)) {
			//read line by line and get user and password pairs
			$line = fgets($fileHandle, filesize($fileName));
			//split the pair into user and password,
			//then store their md5 hash in assoc array
			$pair = explode(",", $line);
			//var_dump($pair);//see contents
			$userHashPairs[md5(trim($pair[0]))] = md5(trim($pair[1]));
		}
	
	
		fclose($fileHandle);
		//finished importing hashed user/password pairs into assoc array
****************/

		
	
		//get the user input
		if((isset($_POST['username'])) || (isset($_POST['password']))) {
			$username = $_POST['username'];
			$password = $_POST['password'];
			$seshData = '';	
			
			
			if($sqlStm = $dbh->prepare("SELECT Password FROM Customers WHERE CustEmail=?")) {
				$sqlStm->bind_param("s", $username);
				$sqlStm->execute(); //begin searching database for the password hash
				$sqlStm->bind_result($dbPword);
				if($sqlStm->fetch()) {				
					if(($dbPword != NULL) && ($dbPword == $password)) {
						$_SESSION['loggedAs'] = $_POST['username'];
						$_SESSION['attempts'] = 0;
						$_SESSION['lastAttempt'] = time();
						$seshData = session_encode();
						$errorMsg = '';
					}
					else {
						$errorMsg = "LOGIN FAILED";
						$_SESSION['lastAttempt'] = time();
						$_SESSION['attempts'] = $loginAttempts;
						$seshData = session_encode();
					}
				}
				else {
					$errorMsg = "LOGIN FAILED";
					$_SESSION['lastAttempt'] = time();
					$_SESSION['attempts'] = $loginAttempts;
					$seshData = session_encode();
				}
				$sqlStm->close();
			}
			
			//changed to access password from database
			//now check for a valid user
			
/*			foreach($userHashPairs as $user => $pass) {
				if(($username == $user) && ($password == $pass)) {
					//found matching username/password pair
					$_SESSION['loggedAs'] = $_POST['username'];
					$_SESSION['attempts'] = 0;
					$_SESSION['time'] = time();
					$seshData = session_encode();
				
					//header("Location: $goHere")
						
					$errorMsg = '';

					break;
				}
				
				else {
					$errorMsg = "LOGIN FAILED";
					$_SESSION['lastAttempt'] = time();
					$_SESSION['attempts'] = $loginAttempts;
					$seshData = session_encode();
					}
				}
*/
			if(isset($firstTime)) {//insert if first time to site
				if($sqlStm = $dbh->prepare("INSERT INTO Sessions(ipAddr, seshId) VALUES(?, ?)")) {
					$sqlStm->bind_param("ss", $remoteAddr, $seshData);
					$sqlStm->execute();//store the session
					$sqlStm->close(); //release resources
				}
			}
			else {//need to update db with new session
				if($sqlStm = $dbh->prepare("UPDATE Sessions SET seshId=? WHERE ipAddr=?")) {
					$sqlStm->bind_param("ss", $seshData, $remoteAddr);
					$sqlStm->execute();
					$sqlStm->close();
				}
			}

			//finished with db, close it
			$dbh->close();

			if(isset($_SESSION['loggedAs'])) {
				echo '<div style="padding-top:20px">
						Welcome back, '.$_SESSION['loggedAs'].'</div>';
			}
			else if($loginAttempts < 5 ) {
				echo "<form method=\"post\" action=\"\">
						<input type=\"hidden\" name=\"attempts\" value=\"$loginAttempts\">
						<table style=\"font-size:80%\">
							<tr><td style=\"text-align:justify\">USER NAME:</td>
							<td><input style=\"text-align:right\" type=\"text\" name=\"username\"></td></tr>
					
							<tr><td style=\"text-align:justify\">PASSWORD:</td>
							<td><input style=\"text-align:right\" type=\"password\" name=\"password\"></td></tr>
					
							<tr><td><div style=\"color:red;font-weight:150;text-align:right\">
								$errorMsg</div></td>
							<td style=\"text-align:right;color:black\"><input type=\"submit\" name=\"submit\" value=\"LOGIN\"> 
							</td></tr>
						</table>
					</form>";
			}
			else { 
			echo '<div style="color:red;font-weight:200;text-align:center;
						padding-top:30px;padding-right:5px">
							ACCESS DENIED</div>';
			}
		}
		
		else {//it's the first time they are visiting
			if($loginAttempts < 5) {
				echo "<form method=\"post\" action=\"\">
						<input type=\"hidden\" name=\"attempts\" value=\"0\">
						<table style=\"font-size:80%\">
							<tr><td style=\"text-align:justify\">USER NAME:</td>
							<td><input style=\"text-align:right\" type=\"text\" name=\"username\"></td></tr>
				
							<tr><td style=\"text-align:justify\">PASSWORD:</td>
							<td><input style=\"text-align:right\" type=\"password\" name=\"password\"></td></tr>
					
							<tr><td colspan=\"2\" style=\"text-align:right\">
								<div style=\"color:red;font-weight:150;text-align:right;padding-right:10px\">
									$errorMsg</div>
								<input style=\"color:black\" type=\"submit\" name=\"submit\" value=\"LOGIN\"> 
							</td></tr>
						</table>
					</form>";
			}
			else {
				echo '<div style="color:red;font-weight:200;text-align:center;
						padding-top:30px;padding-right:5px">
							ACCESS DENIED</div>';
			}
		}
	}
	
	else { //someone is logged in
		//check to see if their session has timed out yet
		$last = time() - $_SESSION['lastAttempt'];
		if($last < $loggedTOut) {
			echo '<div style="text-align:center;padding-right:5px">
				Welcome back, '.$_SESSION['loggedAs'].'</div>';
		}
		else { //timed out, ask them to login again
			unset($_SESSION['loggedAs']);
			$_SESSION['attempts'] = 0;
			$_SESSION['time'] = time();
			$seshData = session_encode();
			if($sqlStm = $dbh->prepare("UPDATE Sessions SET seshId=? WHERE ipAddr=?")) {
					$sqlStm->bind_param("ss", $seshData, $remoteAddr);
					$sqlStm->execute();
					$sqlStm->close();
			}
			
			
			echo "<form method=\"post\" action=\"\">
					<input type=\"hidden\" name=\"attempts\" value=\"$loginAttempts\">
					<table style=\"font-size:80%\">
						<tr><td style=\"text-align:justify\">USER NAME:</td>
						<td><input style=\"text-align:right\" type=\"text\" name=\"username\"></td></tr>
				
						<tr><td style=\"text-align:justify\">PASSWORD:</td>
						<td><input style=\"text-align:right\" type=\"password\" name=\"password\"></td></tr>
					
						<tr><td><div style=\"color:red;font-weight:150;text-align:right\">
							SESSION TIMED OUT</div></td>
						<td style=\"text-align:right;color:black\"><input type=\"submit\" name=\"submit\" value=\"LOGIN\"> 
						</td></tr>
					</table>
				</form>";			
		}
		$dbh->close(); //don't need db anymore
	}


?>